import { Provide, Inject } from '@midwayjs/core';
import { BaseService, CoolCommException } from '@cool-midway/core';
import { InjectEntityModel } from '@midwayjs/typeorm';
import { Repository, In } from 'typeorm';
import { ProviderCustomerEntity } from '../entity/customer';
import { UserInfoEntity } from '../../user/entity/info';
import { Context } from '@midwayjs/koa';
import { CreateCustomerDTO, UpdateCustomerDTO } from '../dto/customer';

@Provide()
export class ProviderCustomerService extends BaseService {
    @InjectEntityModel(ProviderCustomerEntity)
    providerCustomerEntity: Repository<ProviderCustomerEntity>;

    @InjectEntityModel(UserInfoEntity)
    userInfoEntity: Repository<UserInfoEntity>;

    @Inject()
    ctx: Context;

    /**
     * 添加客户
     */
    async add(dto: CreateCustomerDTO) {
        const teamId = this.ctx.team?.id;
        if (!teamId) {
            throw new CoolCommException('请先创建或加入团队');
        }

        // 检查是否已存在
        const exist = await this.providerCustomerEntity.findOne({
            where: { teamId, phone: dto.phone }
        });

        if (exist) {
            throw new CoolCommException('该用户已在客户列表中');
        }

        // 自动填充用户信息
        if (!dto.name || !dto.phone) {
            const user = await this.userInfoEntity.findOne({ where: { id: dto.userId } });
            if (user) {
                dto.name = dto.name || user.nickName;
                dto.phone = dto.phone || user.phone;
            }
        }

        return await this.providerCustomerEntity.save({
            ...dto,
            teamId,
            status: 1
        });
    }

    /**
     * 修改客户信息
     */
    async update(dto: UpdateCustomerDTO) {
        const teamId = this.ctx.team?.id;
        const customer = await this.providerCustomerEntity.findOne({
            where: { id: dto.id, teamId }
        });

        if (!customer) {
            throw new CoolCommException('客户不存在');
        }

        await this.providerCustomerEntity.save({
            ...customer,
            ...dto
        });
    }

    /**
     * 客户列表
     */
    async page(query: any) {
        const { page = 1, size = 20, keyWord, isStar } = query;
        const teamId = this.ctx.team?.id;

        if (!teamId) {
            return { list: [], pagination: { page, size, total: 0 } };
        }

        const queryBuilder = this.providerCustomerEntity.createQueryBuilder('a')
            .where('a.teamId = :teamId', { teamId });

        if (keyWord) {
            queryBuilder.andWhere('(a.name LIKE :keyWord OR a.phone LIKE :keyWord OR a.remark LIKE :keyWord)', { keyWord: `%${keyWord}%` });
        }

        if (isStar !== undefined && isStar !== '') {
            queryBuilder.andWhere('a.isStar = :isStar', { isStar });
        }

        const [list, total] = await queryBuilder
            .orderBy('a.createTime', 'DESC')
            .skip((page - 1) * size)
            .take(size)
            .getManyAndCount();

        // 关联用户信息
        if (list.length > 0) {
            const userIds = list.map(e => e.userId);
            const users = await this.userInfoEntity.find({
                where: { id: In(userIds) },
                select: ['id', 'nickName', 'avatarUrl', 'phone']
            });
            const userMap = new Map(users.map(u => [u.id, u]));

            list.forEach((item: any) => {
                const user = userMap.get(item.userId);
                item.userInfo = user || null;
                // 如果没填联系方式，尝试使用用户注册手机号
                if (!item.phone && user?.phone) {
                    item.phone = user.phone;
                }
            });
        }

        return {
            list,
            pagination: {
                page,
                size,
                total
            }
        };
    }
    
    /**
     * 启用/禁用
     */
    async status(id: number, status: number) {
        const teamId = this.ctx.team?.id;
        const customer = await this.providerCustomerEntity.findOne({
            where: { id, teamId }
        });
        if (!customer) {
             throw new CoolCommException('客户不存在');
        }
        await this.providerCustomerEntity.update(id, { status });
    }
}

